<script setup lang="ts">
import type {Cropper, CropperResult} from './typing';

import {ref} from 'vue';
import {Upload, message} from 'ant-design-vue';
import {BasicAvatar, BasicButton, BasicIcon} from '#/components/shadcn-ui';
import {useModal} from '#/ui-kit';
import {dataURLtoBlob} from '#/utils';

// import {upload} from '#/api/file';

import CropperImage from './cropper-image.vue';

const emits = defineEmits(['update']);

const cropper = ref<Cropper>();
const avatar = ref('');
const preview = ref('');
let filename = '';
let scaleX = 1;
let scaleY = 1;

const [Modal, modalApi] = useModal({
  confirmText: '确认并上传',
  closeOnClickModal: false,
  closeOnPressEscape: false,
  fullscreenButton: false,
  onOpenChange: (isOpen) => {
    if (isOpen) {
      avatar.value = modalApi?.getData()?.avatar;
    }
  },
  onConfirm: () => {
    handleConfirm();
  }
});

const handleConfirm = async () => {
  modalApi.setState({confirmLoading: true});
  try {
    const blob = dataURLtoBlob(preview.value);
    message.warn('上传功能接口暂未实现，请至 cropper-modal.handleConfirm() 中自行实现');
    // await upload({file: blob, filename}).then(res => {
    //   emits('update', res.url);
    //   modalApi.close();
    // });
  } finally {
    modalApi.setState({confirmLoading: false});
  }
}

const handleBeforeUpload = (file) => {
  const reader = new FileReader();
  reader.readAsDataURL(file);
  avatar.value = '';
  preview.value = '';
  reader.onload = function (e) {
    avatar.value = (e.target?.result as string) ?? '';
    filename = file.name;
  };
  return false;
}

const handleToolbar = (event, arg) => {
  if (event === 'scaleX') {
    scaleX = arg = scaleX === -1 ? 1 : -1;
  }
  if (event === 'scaleY') {
    scaleY = arg = scaleY === -1 ? 1 : -1;
  }
  (cropper?.value as any)?.[event]?.(arg);
}

const handleReady = (instance) => {
  cropper.value = instance;
}

const handleCropend = ({imgBase64}: CropperResult) => {
  preview.value = imgBase64;
}
</script>
<template>
  <Modal>
    <div class="flex">
      <div class="w-[55%] h-[340px]">
        <div
            class="h-[300px] bg-gray-100 bg-[linear-gradient(45deg,rgba(0,0,0,0.25)_25%,transparent_0,transparent_75%,rgba(0,0,0,0.25)_0),linear-gradient(45deg,rgba(0,0,0,0.25)_25%,transparent_0,transparent_75%,rgba(0,0,0,0.25)_0)_0_0] bg-[length:24px_24px]">
          <CropperImage v-if="avatar" :src="avatar" :height="300" @reday="handleReady" @cropend="handleCropend"/>
        </div>
        <div class="flex justify-between items-center mt-2.5">
          <Upload :show-upload-list="false" accept="image/*" :before-upload="handleBeforeUpload">
            <BasicButton size="icon" class="h-[24px] w-[30px]" v-tippy="{content: '选择图片', placement: 'bottom'}">
              <BasicIcon class="h-[14px] w-[14px]" icon="ant-design:upload-outlined"/>
            </BasicButton>
          </Upload>

          <div class="grid grid-cols-7 gap-1 gap-x-3">
            <BasicButton size="icon" class="h-[24px] w-[30px]" :disabled="!avatar"
                         v-tippy="{content: '重置', placement: 'bottom'}" @click="handleToolbar('reset')">
              <BasicIcon class="h-[14px] w-[14px]" icon="ant-design:reload-outlined"/>
            </BasicButton>

            <BasicButton size="icon" class="h-[24px] w-[30px]" :disabled="!avatar"
                         v-tippy="{content: '逆时针旋转', placement: 'bottom'}" @click="handleToolbar('rotate', -45)">
              <BasicIcon class="h-[14px] w-[14px]" icon="ant-design:rotate-left-outlined"/>
            </BasicButton>

            <BasicButton size="icon" class="h-[24px] w-[30px]" :disabled="!avatar"
                         v-tippy="{content: '顺时针旋转', placement: 'bottom'}" @click="handleToolbar('rotate',45)">
              <BasicIcon class="h-[14px] w-[14px]" icon="ant-design:rotate-right-outlined"/>
            </BasicButton>

            <BasicButton size="icon" class="h-[24px] w-[30px]" :disabled="!avatar"
                         v-tippy="{content: '水平翻转', placement: 'bottom'}" @click="handleToolbar('scaleX')">
              <BasicIcon class="h-[14px] w-[14px]" icon="vaadin:arrows-long-h"/>
            </BasicButton>

            <BasicButton size="icon" class="h-[24px] w-[30px]" :disabled="!avatar"
                         v-tippy="{content: '垂直翻转', placement: 'bottom'}" @click="handleToolbar('scaleY')">
              <BasicIcon class="h-[14px] w-[14px]" icon="vaadin:arrows-long-v"/>
            </BasicButton>

            <BasicButton size="icon" class="h-[24px] w-[30px]" :disabled="!avatar"
                         v-tippy="{content: '放大', placement: 'bottom'}" @click="handleToolbar('zoom', 0.1)">
              <BasicIcon class="h-[14px] w-[14px]" icon="ant-design:zoom-in-outlined"/>
            </BasicButton>

            <BasicButton size="icon" class="h-[24px] w-[30px]" :disabled="!avatar"
                         v-tippy="{content: '缩小', placement: 'bottom'}" @click="handleToolbar('zoom', -0.1)">
              <BasicIcon class="h-[14px] w-[14px]" icon="ant-design:zoom-out-outlined"/>
            </BasicButton>
          </div>
        </div>
      </div>
      <div class="w-[45%] h-[340px]">
        <div class="w-[220px] h-[220px] mx-auto overflow-hidden rounded-full">
          <img :src="preview" v-if="preview" alt="avatar" class="w-full h-full object-cover"/>
        </div>
        <div class="flex gap-8 mt-4 justify-center items-center">
          <BasicAvatar :src="preview" class="w-[38px] h-[38px]"/>
          <BasicAvatar :src="preview" class="w-[46px] h-[46px]"/>
          <BasicAvatar :src="preview" class="w-[62px] h-[62px]"/>
          <BasicAvatar :src="preview" class="w-[78px] h-[78px]"/>
        </div>
      </div>
    </div>
  </Modal>
</template>

<style scoped lang="scss">
</style>